<template>
  <!--  新闻中心页面-->
  <div class="page">
    <div class="page_main">
      <div style="margin-bottom: 20px;">
        <el-button
          size="small"
          class="common_btn-small"
          icon="el-icon-plus"
          @click="websiteAdd(2,'1475756981923921921')"
        >
          添加新闻
        </el-button>
        <el-button icon="el-icon-sort" @click.stop="handleSortMonitorPoint()" class="common_btn-small">
          新闻排序
        </el-button>
      </div>
      <el-table stripe :data="dataList" border style="width: 100%;">
        <el-table-column label="序号" fixed width="80">
          <template slot-scope="scope">
            {{ getIndex(scope.$index) }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" min-width="120" show-overflow-tooltip
                         label="新闻标题"></el-table-column>
        <el-table-column align="center" prop="detail" min-width="120" show-overflow-tooltip
                         label="详情"></el-table-column>
        <el-table-column label="操作" fixed="right" width="250">
          <template slot-scope="scope">
            <button type="text"
                    class="btn_add"
                    @click.stop="Topping(scope.row.id,)" style="margin-right: 10px">
              置顶
            </button>
            <button type="text"
                    class="btn_add"
                    @click.stop="handleEdit(scope.row,)" style="margin-right: 10px">
              修改
            </button>
            <button type="text"
                    class="btn_add"
                    @click.stop="handleQuill(scope.row,)" style="margin-right: 10px">
              编辑详情
            </button>
            <el-popconfirm :title="scope.row.flag===0?'确定启用该菜单吗':'确定停用该菜单吗'"
                           @confirm="handleValidate(scope.row.id,scope.row.flag===0?1:0)">
              <button :class="scope.row.flag===0?'btn_edit':'btn_delete'" slot="reference" @click.stop>
                {{scope.row.flag===0?'启用':'停用'}}
              </button>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
                     :page-size="form.pageSize"    :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
              layout="sizes, prev, pager, next"  :total="form.total">
      </el-pagination>
    </div>
    <!-- 新增编辑菜单-->

    <el-dialog :title=dialogTitle :visible.sync="isShowDialog1" :close-on-click-modal="false" width="820px">
      <!-- 具体form表单 -->
      <el-form label-position="right" ref="form3" :rules="rules" :model="form3" label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="新闻标题" prop="name">
              <el-input v-model.trim="form3.name" placeholder="输入新闻标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="副标题" prop="subtitle">
              <el-input v-model.trim="form3.subtitle" placeholder="输入副标题"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="详情" prop="detail">
          <el-input type="textarea" v-model.trim="form3.detail" placeholder="输入详情"
                    style="min-height: 100px"></el-input>
        </el-form-item>
        <el-form-item label="上传新闻相关图" prop="picture" style="width: 100%!important;">
          <upload-img v-model="form3.picture" :limit="2" :size-limit="2"
                      ref="uploadPic"></upload-img>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
           <el-button class="common_btn-white" @click="isShowDialog1 = false">取消</el-button>
        <el-button type="primary" class=" common_btn-defalut1" @click="validateForm"
                   style="background:#1990FE">提 交
        </el-button>
    </span>
    </el-dialog>
    <!-- 编辑富文本-->
    <el-drawer :wrapperClosable="false"  title='编辑富文本' :visible.sync="isShowDialog2" :close-on-click-modal="false" size="50%" direction="ltr"
               style="text-align: center">
      <div class="demo-drawer__content">
        <editor-drawer ref="editorDrawer" @submitClose="submitClose"></editor-drawer>
      </div>
      <div class="demo-drawer__footer" style="text-align: right;">
        <el-button class="common_btn-white" @click="isShowDialog2 = false">取消</el-button>
        <el-button type="primary" class=" common_btn-defalut1" @click="submitDrawer"
                   style="background:#1990FE">提 交
        </el-button>
      </div>
    </el-drawer>
    <!--    菜单排序-->
    <el-dialog title="新闻排序" :visible.sync="isShowDialog" :close-on-click-modal="false" width="220px">
      <div style="text-align: center;color: #ff4d51;margin-bottom: 10px;font-size: 15px">从上至下进行排序，拖拽改变顺序，提交后生效！</div>
      <el-tree
        :data="monitorSortList"
        node-key="id"
        default-expand-all
        highlight-current
        :allow-drop="allowDrop"
        draggable>
        <span class="custom-tree-node" slot-scope="{ node }">
            <span>
                <i class="el-icon-s-flag" style="margin-right: 10px;color: #1990FE"></i>{{ node.label }}
            </span>
        </span>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button class="common_btn-white" @click="isShowDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="sortSubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<script>
  import constUrl from '@/services/env'
  import {
    getWebsiteList,
    getWebsiteAdd,
    getWebsiteUpdate,
    getWebsiteValidate,websitePointSort
  } from '@/services/model/website'
  import UploadImg from '@/components/upload-img'
  import editorDrawer from './editor-drawer'
  import {getDictData} from '@/services/model/common'
  import Format from '@/utils/format'
  // form表单校验规则
  const RULES = {
    name: {required: true, message: '请输入菜单名称'},
    type: {required: true, message: '请选择菜单类型'},
    level: {required: true, message: '请输入菜单等级'},
  };
  export default {
    components: {
      UploadImg, editorDrawer
    },
    data() {
      return {
        form: {
          page: 1,
          pageSize: 10,
        },
        childList: [],//table数据
        editableTabsValue: 0, //tab默认展示
        constUrl,
        type: 1,
        //是否启用
        //菜单类型
        parentId: '',
        EnumWebTypeList: [],
        dataList: [],
        monitorSortList: [],
        isShowDialog: false,
        isShowDialog1: false,
        isShowDialog2: false,
        form3: {richText: ''},
        rules: RULES,
        // 接口获取 打开方式
      }
    },
    filters: {
      // 时间格式化
      formatTimer(timer) {
        return Format(new Date(timer))
      }
    },
    computed: {
      // 弹窗的title
      dialogTitle() {
        return this.form3.id ? '编辑新闻' : '新增新闻'
      },
      // 树形菜单
      tableList() {
        let menu = this.$store.state.webList
        // 设置层级
        const _setLevel = (list, index = 1) => list.map(x => {
          x._level = index
          x.subMenu && _setLevel(x.subMenu, index + 1)
          return x
        })
        return _setLevel(menu)

      },
    },
    methods: {
      //打开排序弹窗
      handleSortMonitorPoint() {
        this.monitorSortList = this.dataList.map(x => {
          return {id: x.id, weight: x.weight, label: x.name}
        })
        this.isShowDialog = true
      },
      //拖拽时判定目标节点能否被放置。type 参数有三种情况：'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后
      allowDrop(draggingNode, dropNode, type) {
        //限制拖入节点内
        return type !== 'inner'
      },
      //排序确定事件
      async sortSubmit() {
        let name = []

        let i = this.monitorSortList.length
        //更新排序值
        this.monitorSortList.map(x => {
          x.weight = i
          name.push(x)
          i--
        })
        let res = await websitePointSort(name)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '排序调整成功！'
          })
          this.isShowDialog = false
          this.queryList(this.parentId)

        }
      },
      // 置顶
      async  Topping(id){
        let name = []
        this.monitorSortList=[]
        this.monitorSortList=JSON.parse(JSON.stringify(this.dataList))
        let i =  this.monitorSortList.length
        //更新排序值
        this.monitorSortList.map((item,index) => {
          if(item.id == id){
            item.weight = i
            this.monitorSortList.unshift( this.monitorSortList.splice(index , 1)[0]);
          }
        })
        this.monitorSortList.map(x => {
          x.weight = i
          name.push(x)
          i--
        })
        let res = await websitePointSort(name)
        if (res.code === 200) {
          this.$notify({
            type: 'success',
            title: '提示',
            message: '排序调整成功！'
          })
          this.isShowDialog = false
          this.queryList(this.parentId)

        }
      },
      //富文本提交按钮
      submitDrawer() {
        this.$refs.editorDrawer.submitData(this.form3, '产品')
      },
      submitClose() {
        this.isShowDialog2 = false
        this.queryList()
      },
      // 分页大小改变
      handleSizeChange(val) {
        this.form.pageSize = val
        this.queryList()
      },
      // 当前页码改变
      handleCurrentChange(val) {
        this.form.page = val
        this.queryList()
      },
      // 获取当前的序号
      getIndex(index) {
        let param = (this.form.page - 1) * this.form.pageSize + index + 1;
        return param;
      },
      //获取子列表数据
      async changeTab() {
        let id = this.dataList[this.editableTabsValue].id
        this.form = {page: 1, pageSize: 15, parentId: id}
        const {data} = await getWebsiteList(this.form)
        this.childList = data.records
        this.form.page = Number(data?.current)
        this.form.total = Number(data?.total)
      },
      //删除tab
      removeTab(targetName) {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
              }
            }
          });
        }
        this.editableTabsValue = activeName;
        this.editableTabs = tabs.filter(tab => tab.name !== targetName);
      },
      // 通用获取枚举方法
      async queryDicts() {
        const {data} = await getDictData({enumName: 'EnumWebType'})
        this.EnumWebTypeList = data || []
      },
      // 新增菜单按钮
      websiteAdd(level, parentId) {
        this.form3 = {type: 1, level: level, parentId: parentId}
        this.isShowDialog1 = true
        this.$nextTick(() => {
          this.$refs.form3.clearValidate()
          this.$refs.uploadPic.clears()

        })
      },
      //停用
      async handleValidate(id, flag) {
        await getWebsiteValidate({id: id, flag: flag})
        this.$notify({
          title: '提示',
          message: '停用成功',
          type: 'success'
        })
        this.queryList()

      },
      // 修改 按钮
      handleEdit(item) {
        this.isShowDialog1 = true
        this.form3 = JSON.parse(JSON.stringify(item))
        if(this.$refs.uploadPic){
          this.$refs.uploadPic.clears()
        }
        this.$nextTick(() => {
          this.$refs.form3.clearValidate()
        })
      },
      //打开富文本编辑
      handleQuill(item) {
        this.form3 = JSON.parse(JSON.stringify(item))
        this.isShowDialog2 = true
        this.$nextTick(() => {
          this.$refs.editorDrawer.changeRichText(this.form3)

        })
      },
      // 表单提交
      validateForm() {
        this.$refs.form3.validate((valid) => {
          valid && this.submitData()
        })
      },
      // 新增编辑提交数据
      async submitData() {
        // 根据ID判断使用新增还是编辑
        this.form3.type=1
        const AJAX_ACTION = this.form3.id ? getWebsiteUpdate : getWebsiteAdd
        await AJAX_ACTION(this.form3)
        this.$notify({
          type: 'success',
          title: '提示',
          message: this.form3.id ? '编辑成功' : '添加成功'
        })
        this.isShowDialog1 = false
        this.isShowDialog2 = false
        if (this.form3.parentId !== '') {
          this.queryList(this.form3.parentId)
        } else {
          this.queryList()
        }

      },
      // 查询tab
      async queryList() {
        const {data} = await getWebsiteList({page: 1, pageSize: 15, parentId: '1475756981923921921'})
        this.dataList = data.records
        this.changeTab(this.dataList[0].id)
      }
    },
    mounted() {
      this.queryDicts()
      this.queryList()
    },
  }
</script>
<style lang="less">


</style>
<style scoped lang="less">
  .page {
    height: 100%;
    padding: 24px;
    overflow-x: hidden;
    overflow-y: auto;
  }

  .caseBox {
    width: 100%;
    text-align: center;
    margin-top: 2vh;
    height: 70vh !important;
    overflow: auto;

    .ql-editor {
      width: 100%;
      overflow-y: auto;
      box-sizing: border-box;
    }
  }


  /*修改富文本编辑器样式*/
  /deep/ .ql-toolbar.ql-snow + .ql-container.ql-snow {
    height: 88%;
    overflow-y: hidden;
  }

  /deep/ .el-textarea, /deep/ .el-textarea__inner {
    min-height:100px !important;
  }
  /*修改表单样式*/
  .demo-drawer__content {
    height: 85vh;
    overflow-y: auto;

    /deep/ .el-form {
      width: 80%;
      margin: auto;
      overflow-y: auto;
      align-items: center;
      justify-content: space-between;
      flex-wrap: wrap;
      margin-top: 50px;
      text-align: left
    }


  }
</style>
